package com.sit.library.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.sit.library.entity.bean.Book;
import com.sit.library.entity.bean.BorrowRecord;
import com.sit.library.entity.dao.BookMapper;
import com.sit.library.entity.dao.BorrowMapper;
import com.sit.library.entity.vo.response.BorrowRecordVO;
import com.sit.library.service.UserService;
import com.sit.library.utils.JwtUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private BookMapper bookMapper;

    @Resource
    private BorrowMapper borrowMapper;

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public List<Book> getBooks() {
        return bookMapper.findAll();
    }

    @Override
    public List<Book> getBooksByTitle(String title) {
        return bookMapper.findByTitle("%" + title + "%");
    }

    @Override
    public String borrowBook(String token, int bookId) {
        DecodedJWT jwt = jwtUtils.resolveJwt(token);
        Integer userId = jwt.getClaim("id").asInt();
        return borrowMapper.borrowBook(userId, bookId);
    }

    @Override
    public String returnBook(String token, int recordId) {
        DecodedJWT jwt = jwtUtils.resolveJwt(token);
        Integer userId = jwt.getClaim("id").asInt();
        return borrowMapper.returnBook(recordId, userId);
    }

    @Override
    public List<BorrowRecordVO> getBorrowRecords(String token) {
        DecodedJWT jwt = jwtUtils.resolveJwt(token);
        Integer userId = jwt.getClaim("id").asInt();
        List<BorrowRecord> records = borrowMapper.findByUser(userId);
        List<BorrowRecordVO> vos = new ArrayList<>();
        for (BorrowRecord record : records) {
            BorrowRecordVO vo = new BorrowRecordVO();
            vo.setId(record.getId());
            vo.setBookId(record.getBookId());
            vo.setBorrowDate(record.getBorrowDate());
            vo.setReturnDate(record.getReturnDate());
            vo.setTitle(bookMapper.findById(record.getBookId()).getTitle());
            vos.add(vo);
        }
        return vos;
    }
}
